//
//  ST_SettingBeautyFIlterController.swift
//  btvideo
//
//  Created by mac on 2021/3/24.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SwiftyUserDefaults
import NERtcSDK
import SwiftyJSON


class ST_SettingBeautyFIlterController: UIViewController  {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .black
        
        KC_initRTCEngine()
        make_u_i()
        binding()
        pull_data()
    }
    
    deinit{
        
        DispatchQueue.global().async {
            
            NEBeautyManager.shared().destroyNEBeauty()

        }
        
        /// RS 测试为异步会导致未知问题，先修改成同步调用
        NERtcEngine.destroy()
        
        print("#ST_SettingBeautyFIlterController deinit")
    }
    
//MARK: - Properties
    private lazy var close_button : UIButton = {
        let button = UIButton()
        button.setImage(ST_ImageUtils.imageName("返回_white"), for: UIControl.State.normal)
        return button
    }()
    
    private lazy var beauty_btn:UIButton = {
        let b = UIButton.init(type: UIButton.ButtonType.custom)
        b.setTitle("【设置美颜】", for: .normal)
        b.alpha = 0
        return b
    }()
    
    private lazy var big_video_view:UIView = {
        let i = UIView()
        return i
    }()
    
    private lazy var engin_context:NERtcEngineContext = {
        let context = NERtcEngineContext()
        context.engineDelegate = self
        context.appKey = PH.nimAppID
        //默认情况下日志会存储在App沙盒的Documents目录下
        let logSetting = NERtcLogSetting()
    #if DEBUG
        logSetting.logLevel = .info
    #else
        logSetting.logLevel = .warning
    #endif
        context.logSetting = logSetting
        return context
    }()
    
    private var engine:NERtcEngine{
        return NERtcEngine.shared()
    }
}

extension ST_SettingBeautyFIlterController{
    
    
    private func KC_initRTCEngine(){
        
        self.engine.setupEngine(with: self.engin_context)
        
        //初始化美颜模块
        //开启美颜功能
        NEBeautyManager.shared().initNEBeauty()
        NEBeautyManager.shared().enableNEBeauty(true)
    }
    
    private func binding(){
        
        
        close_button.rx.tap.withUnretained(self).subscribe { own,_ in
            
            own.engine.leaveChannel()
            
            own.goback_previous_controller()
            
        }.disposed(by: rx.disposeBag)
        
        
        beauty_btn.rx.tap.withUnretained(self).subscribe { own,_ in
                
            own.show_beauty_config_view()
            
        }.disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(.beauty_config_closed_noti)
            .withUnretained(self)
            .subscribe(onNext: { own,noti in
                
                own.beauty_btn.alpha = 1
                
            }).disposed(by: rx.disposeBag)
        
    }
    
    private func make_u_i(){
        
        view.addSubviews([big_video_view,close_button,beauty_btn])
        
        big_video_view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        close_button.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(statusBarHeight)
        }
        
        beauty_btn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(38)
            make.centerY.equalToSuperview().offset(100)
        }
        
    }
    private func pull_data(){
        
        
        TIANSession(requestUrl: PH.beautyDanceApi).withUnretained(self).subscribe(onNext: { own,json in
            
            switch json{
            case .success(let jsonValue):
                own.joinChannel(json: jsonValue["data"])
            case .failure(_):
                own.toast(text: "未知错误，请稍后再试！")
            }
            
            
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    private func joinChannel(json:JSON){
        
        
        engine.setAudioProfile(.standard, scenario: .speech)
        let configuration = NERtcVideoEncodeConfiguration()
        configuration.width = 1280
        configuration.height = 720
        configuration.frameRate = .fps15
        engine.setLocalVideoConfig(configuration)
        engine.enableLocalAudio(true)
        engine.enableLocalVideo(true)
        
        let userModel = NTESDemoUserModel()

        userModel.renderContainer = self.big_video_view
        
        NERtcEngine.shared().setupLocalVideoCanvas(userModel.setupCanvas())
        
        
        engine.joinChannel(withToken: json["token"].stringValue, channelName: json["channel_name"].stringValue, myUid: json["id"].uInt64Value) { [weak self] error, channelId, elapesd, uid in
            
            if error != nil{
                
                self?.toast(text: "发送错误，请稍后再试")
                return
            }
            
            self?.show_beauty_config_view()
            
        }
    }
    
    private func show_beauty_config_view(){
        
        NEBeautyManager.shared().displayMenu(with: NEBeautyManager.allBeautyTypes(), container: view)
        
        beauty_btn.alpha = 0
    }
    
}



extension ST_SettingBeautyFIlterController:NERtcEngineDelegateEx{
    
}
